#include "lexic.h"

static void extractRow(lineT *line);
static void extractCmd(lineT *line);
static void extractRest(lineT *line);

string getInput() {
	string line;
	
	printf("=> ");
	line = ConvertToUpperCase(GetLine());
}

lineT handleInput(string input) {
	lineT line;

	line.rest		= "";
	line.cmd			= "";
	line.row			= -1;

	SetScannerString(db->scanner, input);

	extractRow(&line);
	extractCmd(&line);
	extractRest(&line);

	return line;
}

void saveLine(lineT line) {
	int i;

	// TODO: Need to allocate more memory -> extendDatabase(db):
	if (db->lines.size == db->lines.numRows+1)
		Error("There's no space left to store the row.\n");

	// Row exists -> overwrite it:
	if (db->lines.numRows > 0) {
		for (i=0; i<db->lines.numRows; i++) {
			if (line.row != -1 && db->lines.entries[i].row == line.row) {
				db->lines.entries[i] = line;
				return;
			}
		}
	}
	
	// New row:
	db->lines.entries[db->lines.numRows] = line;
	db->lines.numRows++;
}

void deleteLine(lineT line) {
	int i, rowIndex;

	rowIndex = rowToIndex(line.row);
	if (rowIndex == -1) return;

	db->lines.entries[rowIndex].row = NULL;
	db->lines.entries[rowIndex].cmd = NULL;
	db->lines.entries[rowIndex].rest = NULL;
	for (i=rowIndex; i<db->lines.numRows; i++) {
		db->lines.entries[i] = db->lines.entries[i+1];
	}
	db->lines.numRows--;
}

static void extractRow(lineT *line) {
	string token;
	
	token = ReadToken(db->scanner);
	if (isdigit(token[0])) {
	//if (token[0] <= '9' && token[0] >= '0') {
		line->row = StringToInteger(token);
	} else {
		SaveToken(db->scanner, token);
	}
}

/* Stores the command */
static void extractCmd(lineT *line) {
	string token;
	
	token = ReadToken(db->scanner);
	line->cmd = token;
}

/* Stores the restoring data without row number and command name */
static void extractRest(lineT *line) {
	string token;

	SetScannerSpaceOption(db->scanner, PreserveSpaces);
	while (MoreTokensExist(db->scanner)) {
		token = ReadToken(db->scanner);
		line->rest = Concat(line->rest, token);
	}
	SetScannerSpaceOption(db->scanner, IgnoreSpaces);
}